package com.maxd.modules.selfshop.merchants.service;

import com.maxd.error.Result;
import com.maxd.error.ResultUtil;
import com.maxd.model.Orders;
import com.maxd.modules.selfshop.merchants.entity.SelfMargin;
import com.maxd.modules.selfshop.merchants.entity.SelfStore;
import com.maxd.modules.selfshop.merchants.respository.SelfMarginJpaRepository;
import com.maxd.modules.selfshop.merchants.respository.SelfStoreJpaRepository;
import com.maxd.respository.common.CommonRepository;
import com.maxd.respository.selfOrder.OrdersRepository;
import com.maxd.utils.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SelfMarginServiceImpl implements SelfMarginService{
    @Autowired
    private SelfMarginJpaRepository jpaRepository;
    @Autowired
    private CommonRepository commonRepository;
    @Autowired
    private SelfStoreJpaRepository selfStoreJpaRepository;
    @Autowired
    private OrdersRepository ordersRepository;

    @Override
    public Result findAll(Integer page, Integer size, String storeName) {
        //按照时间排序
        Pageable pageable = PageRequest.of(page, size, Sort.by(new Sort.Order(Sort.Direction.DESC, "createTime")));
        //构造自定义查询条件
        Specification<SelfMargin> queryCondition = new Specification<SelfMargin>() {
            @Override
            public Predicate toPredicate(Root<SelfMargin> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                if (StringUtils.isNotEmpty(storeName)) {
                    predicateList.add(criteriaBuilder.like(root.get("storeName"), "%"+storeName+"%"));
                }
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        return ResultUtil.success(jpaRepository.findAll(queryCondition, pageable));
    }

    @Override
    public Result storeList(Integer page, Integer size, Long storeId) {
        //按照时间排序
        Pageable pageable = PageRequest.of(page, size, Sort.by(new Sort.Order(Sort.Direction.DESC, "createTime")));
        //构造自定义查询条件
        Specification<SelfMargin> queryCondition = new Specification<SelfMargin>() {
            @Override
            public Predicate toPredicate(Root<SelfMargin> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                predicateList.add(criteriaBuilder.equal(root.get("storeId"), storeId));
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        return ResultUtil.success(jpaRepository.findAll(queryCondition, pageable));
    }

    /**
     * 保证金缴纳成功
     * @param entity
     * @return
     */
    @Override
    public Result saveBody(SelfMargin entity) {
        SelfStore s = selfStoreJpaRepository.findByMerchantId(entity.getMerchantId());
        s.setMarginStatus(2); //保证金状态：已缴纳
        s.setMarginType(entity.getMarginType());
        if (entity.getMarginType() == 2){
            String endTime = DateUtil.addYears(DateUtil.createDate(), 1);
            s.setEndTime(endTime); //时间计算
            entity.setEndTime(endTime);
        }
        entity.setStoreId(s.getStoreId());
        entity.setCreateTime(DateUtil.createDate());
        selfStoreJpaRepository.save(s); //更新店铺信息
        SelfMargin save = jpaRepository.save(entity);
        return ResultUtil.success(save);
    }

    @Override
    public Result updateBody(SelfMargin entity) {
        return ResultUtil.success(jpaRepository.save(entity));
    }

    @Override
    public Result findOne(Long id) {
        return ResultUtil.success(jpaRepository.findById(id).orElse(null));
    }

    @Override
    public Result delete(Long id) {
        jpaRepository.deleteById(id);
        return ResultUtil.success();
    }

    @Override
    public Result marginList() {
        String value = commonRepository.findOne(108).getValue();
        if ("2".equals(value)){
            return ResultUtil.error(-1, "保证金已关闭");
        }
        String value1 = commonRepository.findOne(109).getValue();
        String value2 = commonRepository.findOne(110).getValue();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("price1", value1);
        map.put("price2", value2);
        return ResultUtil.success(map);
    }

    @Override
    public Result income(String data, int way) {
        List<Orders> list =  ordersRepository.findByStatusAndOrderType();
        switch (way){
            case 1: data = data.substring(0,4); break; //年，截取前四个
            case 2: data = data.substring(0,7); break; //月，前6
            default: break; //日，或者其他不做处理
        }
        BigDecimal sum0 = new BigDecimal("0.00"); //总收入
        BigDecimal sum1 = new BigDecimal("0.00"); //当前收入
        for (Orders o : list) {
            BigDecimal money = o.getPayMoney()== null?new BigDecimal("0.00"):o.getPayMoney(); //订单金额
            sum0 = sum0.add(money);
            if (o.getPayTime().contains(data)){
                sum1 = sum1.add(money);
            }
        }
        int count1 = 0; //店铺个数
        int count2 = 0; //已缴纳店铺
        int count3 = 0; //永久保证金
        int count4 = 0; //年费保证金
        List<SelfStore> allStore = selfStoreJpaRepository.findAll();
        for (SelfStore s : allStore) {
            count1++;
            if (s.getMarginStatus() == 2){ //保证金状态(1未缴纳 2已缴纳)
                count2++;
                if (s.getMarginType() == 1){ //保证金类型（1永久 2年费）
                    count3++;
                }else if (s.getMarginType() == 2){
                    count4++;
                }
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("sum0", sum0); //累计收入
        map.put("sum1", sum1); //当前收入
        map.put("count1", count1); //店铺个数
        map.put("count2", count2); //已缴纳店铺
        map.put("count3", count3); //永久保证金
        map.put("count4", count4); //年费保证金
        return ResultUtil.success(map);
    }

    @Override
    public Result refundMargin(Long orderId) {
        //保证金明细
        SelfMargin m = jpaRepository.findByOrderId(orderId);
        m.setRefundTime(DateUtil.createTime()); //退款到账时间
        jpaRepository.save(m);
        //账号为无保证金状态
        selfStoreJpaRepository.updateMarginStatus(m.getStoreId());
        return ResultUtil.success();
    }
}
